package com.lbw.servlet;

import com.lbw.model.Person;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Properties;

@WebServlet(name = "PersonServlet")
public class PersonServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        // 获取前段传输过来的数据
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String sex = request.getParameter("sex");
        Integer age = Integer.valueOf(request.getParameter("age"));
        String born = request.getParameter("born");
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate bornDate = LocalDate.parse(born, df);
        System.out.println(id + " " + name + " " + sex + " " + age + " " + born);
        Person person = new Person(id, name, sex, age, bornDate);
        request.setAttribute("person", person);
        // 建立一个文件
        File file = new File("/Users/lbw/Desktop/info.properties");
        if (!file.exists()) {
            file.createNewFile();
        }

        // 创建一个输出流，用于写入信息到文件
        Writer writer = null;
        try {
            writer = new FileWriter(file, true);
            Properties properties = new Properties();
            properties.setProperty("id", id);
            properties.setProperty("name", name);
            properties.setProperty("sex", sex);
            properties.setProperty("age", age + "");
            properties.setProperty("born", born);
            properties.store(writer, "Person Information");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
        request.getRequestDispatcher("ch2/show.jsp").forward(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
